package file


import java.io.{BufferedWriter, File, FileOutputStream, FileWriter, OutputStreamWriter}
import scala.collection.mutable
import scala.io.Source
import scala.util.matching.Regex

/**
 * 处理文件，删除特定文件所在行
 */

object FileFilter {
  def main(args: Array[String]): Unit = {
    val files: List[File] = getListOfFiles("F:\\ComputeDb\\shareplex\\shareplex_files_20220728")
    //    val files: List[File] = getListOfFiles("F:\\ComputeDb\\shareplex\\one")
    for (file <- files) {
      println(file)
      val name: String = file.getName
      val fileD = Source.fromFile(file)
      val strings: Iterator[String] = fileD.getLines()
      //设定写入文件
      var fw: FileWriter = null
      val fileW = new File("F:\\ComputeDb\\shareplex\\two\\shareplex_files_20220728\\" + name)
      if (!fileW.exists()) {
        fileW.createNewFile()
      }
      fw = new FileWriter(fileW)
      val bw: BufferedWriter = new BufferedWriter(fw)

      for (line <- strings) {
        val stringsSplit: Array[String] = line.split(";")
        //        println(stringsSplit.toBuffer)
        //设定正则表达式
        val stringMatch = s"APM_PCM_ADM.CURRENTSTATUS".r
        //        println(stringMatch.toBuffer)
        for (splitLine <- Array(stringsSplit)) {
          val buffer: mutable.Buffer[String] = splitLine.toBuffer
          val matches: Iterator[Regex.Match] = stringMatch.findAllMatchIn(buffer.mkString(""))
          if (!matches.hasNext) {
            println(buffer.mkString(";"))
            bw.write(buffer.mkString(";") + ";")
            bw.newLine()
          }

        }

      }
      bw.close()

    }

  }

  /**
   * 获取指定文件夹下的所有文件列表
   *
   * @param dir
   * @return
   */
  def getListOfFiles(dir: String): List[File] = {
    val d = new File(dir)
    if (d.exists && d.isDirectory) {
      d.listFiles.filter(_.isFile).toList
    } else {
      List[File]()
    }
  }

  /**
   * 读取文件内容
   *
   * @param fileName
   */
  def readFile(fileName: File): Unit = {
    val file = Source.fromFile(fileName)

    println(file)
    val strings: Iterator[String] = file.getLines()
    for (line <- strings) {
      //设定正则表达式
      val stringMatch = "APM_PCM_ADM.CURRENTSTATUS".r
      // findAllIn方法返回遍历所有匹配的迭代器
      for (matchString <- stringMatch.findAllIn(line)) {
        //        println(matchString)
        //        println(line)
        val str: String = line.replaceAll("", line)
        var fw: FileWriter = null
        val fileW = new File("F:\\ComputeDb\\shareplex\\two" + file)
        if (!fileW.exists()) {
          fileW.createNewFile()
        }
        fw = new FileWriter(fileW);
        val bw: BufferedWriter = new BufferedWriter(fw);
        bw.write(str);
        //          bw.write("world\n");
        bw.close();
      }


    }
  }


}
